<!--
* @author: lzm
* @date: 2023年12月8日 15:04:10
* @description：单重配置弹窗
* @update: 2023年12月8日 15:04:16
-->
<template>
  <div>
    <el-dialog
      :title="title"
      :visible="showDialog"
      width="536px"
      center
      custom-class="my-dialog hardConfig"
      @close="close"
      :close-on-click-modal='false'
      :close-on-press-escape='false'
      append-to-body>
      <div class="form-top">
        <el-form ref="ruleForm" :rules="rules" label-width="110px" :model="addList">
          <el-form-item label="当前重量">
            <div class="weight-box" style="width: 90%">
              <div class="weight-num">{{weightNum}}g</div>
              <div class="operate">
                <el-button
                  type="primary"
                  @click="peelOffBtn"
                  class="chamfer-corners-8">
                  去皮归零
                </el-button>
                <el-button
                  type="primary"
                  @click="getWeightBtn"
                  class="chamfer-corners-8">
                  获取重量
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="数量" v-if="mergeCount === '1'">
            <div class="weight-box" style="width: 90%">
              <!-- 使用v-if/v-else来切换显示 -->
              <div v-if="!isEditing" class="weight-num">{{ addList.number }}</div>
              <el-input
                v-else
                v-model="addList.number"
                @blur="saveNum"
                placeholder="请输入正整数"
                :min="1"
                ref="numInput"
              ></el-input>

              <div class="operate">
                <el-button
                  type="primary"
                  @click="updateNum"
                  class="chamfer-corners-8">
                  修改数量
                </el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="数量" prop='number' v-else>
            <el-input
              v-model="addList.number"
              placeholder="请输入数量"
              style="width: 90%"
              size="small"
            />
          </el-form-item>
          <el-form-item label="单重">
            <div class="weight-box" style="width: 90%">
              <div class="weight-num">{{singleWeight}}g</div>
            </div>
          </el-form-item>
          <!-- 按钮 -->
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button
                class="dialog-btn"
                size="mini"
                type="primary"
                @click="configBtn"
              >
                确认
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { updateSingleWeight, updateSingleWeightStatus,zero } from '@/api/locatorManage'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '单重配置'
    },
    // 当前库位id
    positionId: {
      type: String,
      default: ''
    },
    // 当前库位数量
    mergeCount: {
      type: String,
      default: ''
    },
    // 物料id
    logisticsId: {
      type: String,
      default: ''
    },
    // websocket数据
    wsData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  data() {
    return {
      addList: {
        number: 0// 数量
      },
      rules:{
        number: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
        ],
      },
      // 当前重量
      weightNum: 0,
      // 单重
      singleWeight: 0,
      isEditing: false, // 控制编辑状态
      hasManualEdit: false,  // 新添加：标记是否手动修改过数量
      manualNumber: null,    // 新添加：存储手动输入的数量

    }
  },
  computed: {},
  watch: {
    addList: {
      handler(val) {
        if (this.mergeCount !== '1') {
          // 合并货位的单重由后台计算
          this.singleWeight=val.number && val.number > 0 ? parseFloat(this.weightNum/val.number).toFixed(2) : 0.00
        }
      },
      deep: true
    },
    wsData: {
      handler(val) {
        this.weightNum = val.message.includes('_') ? val.message.split('_')[0] : (val.message ? val.message : 0)
        if (this.mergeCount === '1') {

          if (this.hasManualEdit && this.manualNumber) {
            console.log(this.manualNumber);
            // this.addList.number = this.manualNumber;
            // 重新计算单重
            // this.singleWeight = this.weightNum > 0 ? parseFloat(this.weightNum / this.manualNumber).toFixed(2) : 0;
          } else {
            console.log(this.hasManualEdit);
            console.log(val.message.includes('_') ? (val.message.split('_')[1] / 100) : 0);
            this.singleWeight=val.message.includes('_') ? (val.message.split('_')[1] / 100) : 0
            // 如果没有手动修改过，使用原来的计算方式
            this.addList.number = this.singleWeight == '0' ? 0 : Math.round(this.weightNum / this.singleWeight);
          }
        }
      },
      deep: true
    },
  },
  methods: {
    // 关闭弹窗清空所有值
    close() {
      updateSingleWeightStatus({ id: this.positionId, status: false })
      this.$emit('update:showDialog', false)
      this.$refs.ruleForm.resetFields()
      this.hasManualEdit = false
      this.manualNumber = null
      this.isEditing = false
      this.addList = {
        number: null
      }
    },
    // 去皮归零
    peelOffBtn() {
      zero({ id: this.positionId }).then(res => {
        if (res.status === '2000') {
          this.$message.success('去皮归零成功！')
        }
      })
    },
    // 获取重量
    getWeightBtn() {
      let info = { id: this.positionId, status: true }
      if (this.mergeCount === '1') {
        info.type = 1
      }
      updateSingleWeightStatus(info).then(res => {
        if (res.status === '2000') {
          this.$message.success('获取重量成功！')
          if (this.hasManualEdit && this.manualNumber && this.weightNum > 0) {
            this.singleWeight = parseFloat(this.weightNum / this.manualNumber).toFixed(2);
          }
        }
      })
    },
    //修改数量
    updateNum(){
      console.log(!this.isEditing);
      // this.isEditing = true;
      this.isEditing = !this.isEditing;
     // this.mergeCount = 1;

      if (this.isEditing) {
        this.$nextTick(() => {
          this.$refs.numInput.focus();
        });
      }
    },
    saveNum() {
      // 验证输入的是否为正整数
      if (!/^[1-9]\d*$/.test(this.addList.number)) {
        this.$message.error('请输入正整数');
        return;
      }

      this.isEditing = true;
      // 标记已经手动修改过
      this.hasManualEdit = true;
      // 保存手动输入的数量
      this.manualNumber = parseInt(this.addList.number);

      // 重新计算单重
      if (this.weightNum > 0) {
        this.singleWeight = parseFloat(this.weightNum / this.manualNumber).toFixed(2);
      }
    },
    // 点击确认按钮
    configBtn() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let info = {
            id: this.logisticsId,
            weight: this.singleWeight
          }
          if (this.mergeCount !== '1') {
            // 由多个货位合并，需要发送到称重屏显示
            info.type = 1
          }
          if (this.hasManualEdit){
            info.type = 1
          }
          console.log(this.hasManualEdit);
          updateSingleWeight(info).then(res => {
            if (res.status === '2000') {
              // 通知父组件重新请求列表数据
              this.$emit('configComplete',this.positionId)
              this.$emit('update:showDialog', false)
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">


.weight-num {
  font-size: 14px;
}

/* 如果需要控制输入框宽度 */
.el-input {
  width: 200px;
}

::v-deep .hardConfig {
  .form-top {
    margin-top: 30px;
    .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before {
      content: '';
    }
  }
  .el-row {
    text-align: center;
  }
  .el-dialog__body {
    padding: 30px 40px;
    .el-form-item__label {
      margin-right: 5px;
      font-size: 18px;
      color: #fff;
      line-height: 48px;
      font-weight: normal;
      padding-left: 24px;
      text-align-last: justify;
    }
    .el-input--small .el-input__inner {
      height: 48px;
      line-height: 48px;
      font-size: 16px;
    }
    .el-form-item__content {
      line-height: 48px;
    }
    .el-input__suffix {
      top: 4%;
      right: 20px;
      .el-button {
        font-size: 17px;
        color: #062343;
        font-weight: 600;
      }
    }
    .dialog-btn {
      margin-top: 10px;
      font-size: 18px;
      height: 40px;
    }
    .weight-box {
      display: flex;
      justify-content: space-between;
      .weight-num {
        margin-left: 16px;
        color: #fff;
        font-size: 18px;
      }
      .operate {
        .el-button {
          font-size: 16px;
        }
      }
    }
  }
}

// 提示弹窗样式
::v-deep .prompt-dialog {
  margin-top: 30vh;
  .el-dialog__body {
    height: 200px;
    text-align: center;
    font-size: 20px;
    color: #fff;
    padding-top: 72px;
  }
}
</style>
